package org.zero.concurrency.demo.example.threadlocal;

import lombok.extern.slf4j.Slf4j;

/**
 * @program: concurrency-demo
 * @description:
 * @author: 01
 * @create: 2018-10-17 15:35
 **/
@Slf4j
public class RequestHolder {

    private final static ThreadLocal<Long> REQUEST_HOLDER = new ThreadLocal<>();

    /**
     * 添加数据
     *
     * @param id id
     */
    public static void add(Long id) {
        log.info("RequestHolder add value is {}", id);
        // ThreadLocal 内部维护一个map，key为当前线程id，value为当前set的变量
        REQUEST_HOLDER.set(id);
    }

    /**
     * 会通过当前线程id获取数据
     *
     * @return id
     */
    public static Long getId() {
        return REQUEST_HOLDER.get();
    }

    /**
     * 移除变量信息
     * 如果不移除，那么变量不会释放掉，会造成内存泄漏
     */
    public static void remove() {
        REQUEST_HOLDER.remove();
    }
}
